<?php
/**
 * 产品关键字段: 
 * 
 * goods_sn,	goods_name,	original_img,	shop_price,	cost_price,	cat_id,	brand_id
 * 
 * 需要采集的字段:
 * 
 * goods_sn, 产品编号(可选项)
 * goods_name, 产品名称
 * original_img, 产品图片
 * 
 * 范米粒自定义的:
 * 
 * shop_price，销售价
 * cost_price, 成本价
 * cat_id, 范米粒商城的类别编号
 * brand_id, 范米粒商城的品牌编号
 * 
 * SQL 入库语句
 * INSERT INTO `tp_goods` (goods_sn, goods_name, original_img, shop_price, cost_price, cat_id, brand_id)
 * VALUES ("290543TQ",'Birthday Blooms Stud Earrings, December, Turquoise', "/public/upload/goods/2017/07-17/290543TQ.jpg",502.50,455.60,849,357);
 *
 * 其他要抓的网站
 * Coach，Nike，Adidas，Costco，MK
 */ 
namespace app\bee\controller;
use think\Controller;
use think\Cache;
use \DOMDocument;
use \DateTime;

//define('UPLOAD_PATH', ROOT_PATH . "public/upload/goods/");
class Kaola extends BeeController {
  public function index() {
    $url = "http://www.kaola.com/activity/detail/29639.shtml?ri=18467&rt=picture&zid=zid_6234809196&zp=picture2&zn=分流";
    //"http://www.kaola.com/activity/detail/11990.shtml?zn=top&zp=category-1";
    $productsInfo = $this->getProductsInfo($url);
    
    // 测试输出
    var_dump($productsInfo['products'][0]);
    
    return "考拉爬虫";
  }
  public function brands() {
    $brands = [
      "Gerber",
      "MeadJohnson",
      "COACH",
      "Coppertone",
      "CALIFORNIA BABY",
      "Kiehl's",
      "ESTĒE LAUDER",
      "BURT'S BEES",
      "Centrum",
      "Ray Ban",
      "EARTH'S BEST",
      "PALMER'S",
      "NORDIC NATURALS",
      "babyganics",
      "Aveeno",
      "Schiff",
      "Culturelle",
      "Lansinoh",
      "MICHAEL KORS",
      "kate spade",
      "TOMMY HILFIGER",
      "CLINIQUE",
      "thinkbaby",
      "ElizabethArden",
      "Marmot",
      "REBECCA MINKOFF",
      "beats by dr dre",
      "LA MER",
      "iRobot",
      "VICTORIA'S SECRET",
      "ALEXANDER WANG",
      "EASTPAK",
      "TUMI",
      "Puritan's Pride",
    ]
  }
  public function genProductsInfoUS(){
    
  }
  private function getProductsInfo($url) {
    $reuslt = array();
    $doc = new DOMDocument();
    
    $response = $this->request($url);
    
    // 兼容 HTML 错误语法
    libxml_use_internal_errors(true);
    
    $doc->loadHTML($response);
    $divs = $doc->getElementsByTagName("div");
    foreach ($divs as $div) {
      if (strpos($div->getAttribute('class'), 'detailWrap ') !== false) {
        $data = array();
        
        $link_containers = $div->getElementsByTagName('a');
        foreach ($link_containers as $link_contianer) {
          
          // 获取链接
          if ($link_contianer->getAttribute('class') == 'pic') {
            $goods_sn_parts = explode(
              '.', 
              substr(
                $link_contianer->getAttribute('href'), 
                strlen('//www.kaola.com/product/')
              )
            );
            $data['goods_sn'] = $goods_sn_parts[0];
          }
          
          // 获取标题
          if ($link_contianer->getAttribute('class') == 'titLink') {
            $data['goods_name'] = $link_contianer->nodeValue;
          }
          
        }
        
        // 获取图片
        $img_containers = $div->getElementsByTagName('img');
        // var_dump($img_containers);
        foreach ($img_containers as $img_contianer) {
          // var_dump($price_contianer);
          //if ($price_contianer->getAttribute('class') == 'titLink') {
            $url = $img_contianer->getAttribute('data-src');
            $download_report = $this->downloadImageByProductUrl($url, $data['goods_sn']);
            $data['original_img'] = $download_report['image_url'];
          // }
        }
        
        // 获取价格
        
        /**
         * 考拉价格做了加密，无法通过 PHP 获取
         * 可以考虑用 JavaScript 通过前端方式来获取，然后整合到后端抓取到的数据就行
         * 
         * 比如数据库中有产品 goods_sn123 没有价格信息
         * 这时候我们用 JavaScript 获取到数据信息:
         *
         * goods_sn123, 123.45 RMB
         *
         * 通过 SQL 来更新: 
         * UPDATE tp_goods 
         * WHERE goods_sn = {用来匹配 ID} 
         * SET shop_price = {JavaScript 抓取到到数据}
         * 
         * 就可以利用 Sublime 的行选择工具，批量修改每行的数据，以 SQL 语句方式来呈现
         * UPDATE tp_goods WHERE goods_sn = 'goods_sn123' SET shop_price = 123.45
         * 
         * 进入 phpmyadmin 的 SQL 工具，输入上面的 SQL 语句
         */
        
//         $price_containers = $div->getElementsByTagName('strong');
//         // var_dump($img_containers);
//         foreach ($price_containers as $price_contianer) {
//           // var_dump($price_contianer);
//           //if ($price_contianer->getAttribute('class') == 'titLink') {
//             $data['shop_price'] = $price_contianer->getAttribute('data-src');
//           // }
//         }
        


        
        $result['products'][] = $data;
      }
    }
    return $result;
  }

  private function downloadImageByProductUrl($url, $file_name) {
    
    $date_time = new DateTime();
    $upload_path = ROOT_PATH . "public/upload/goods/";
    $image_path = $upload_path . $date_time->format('Y/m-d') . '/';
    //$url = "http://www.pandora.net/assets/packshot?sku={$id}&format=jpg&width=1000&height=1000";
    $url =  preg_replace('/thumbnail=(.*)$/', 'thumbnail=800x800', $url);
    $fh = fopen('http:'.$url, 'r');

    $file_path = $image_path . $file_name . ".jpg";
    // 创建文件夹
    if (!is_dir($image_path)){
      mkdir($image_path, 0777, true);
    }
    if (!file_exists($file_path)) {
      $result['file_put_contents'] = file_put_contents($file_path, $fh);
    } 
    $result['image_url'] = substr($file_path, strlen(ROOT_PATH));
    return $result;
  }
}